package com.lhy.admin.web;


import com.lhy.admin.Constants;
import com.lhy.admin.common.secure.exception.UnAuthorizedException;
import com.lhy.admin.model.Role;
import com.lhy.admin.model.User;
import com.lhy.admin.model.UserRole;
import com.lhy.admin.service.PermissionService;
import com.lhy.admin.service.RoleService;
import com.lhy.admin.service.UserRoleService;
import com.lhy.admin.service.UserService;
import com.lhy.admin.util.AuthUtil;
import com.lhy.admin.util.StringUtil;
import com.lhy.commonweb.model.ResponseResult;
import com.lhy.commonweb.model.ResponseValidate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
public class LoginController {

    @Autowired
    HttpSession session;

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    AuthUtil authUtil;

    /**
     * @param
     * @return com.lhy.commonweb.model.ResponseResult
     * @throws
     * @Title: authorizationCheck
     * @Description: 前端请求该方法验证用户是否登录
     * @date 2018/6/1 16:42
     */
    @RequestMapping(value = "authorization-check", method = RequestMethod.GET)
    public ResponseResult authorizationCheck() {
        if (session.getAttribute(Constants.SESSION_USER_KEY) == null) {
            throw new UnAuthorizedException("unLogin");
        }
        return ResponseResult.ok();
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ResponseResult login(String name, String pass) {
        User user = userService.login(name, pass);
        if (user != null) {
            session.setAttribute(Constants.SESSION_USER_KEY, user);
            List<Role> roles = roleService.listRolesByUserName(user.getName());
            if (!roles.isEmpty()) {
                authUtil.setSessionRoleAndPermission(user, roles);
            } else {
                //没查到角色的默认赋值游客角色
                userRoleService.add(new UserRole().setUserId(new BigDecimal(user.getId()).longValue()).setRoleId(Constants.ANONYMOUS_ROLE_ID));
                Role role = roleService.get(new BigDecimal(Constants.ANONYMOUS_ROLE_ID).intValue());
                roles.add(role);
                authUtil.setSessionRoleAndPermission(user, roles);
            }
            return ResponseResult.ok().setData(user);
        }
        return ResponseResult.fail();
    }

    @RequestMapping(value="logout",method = RequestMethod.GET)
    public ResponseResult logout() {
        session.invalidate();
        return ResponseResult.ok();
    }

    @RequestMapping(value = "exists",method = RequestMethod.POST)
    public ResponseValidate exists(@RequestParam(value = "name", required = false) String name,
                                   @RequestParam(value = "phone", required = false) String phone,
                                   @RequestParam(value = "email", required = false) String email) {
        User user = null;
        String msg = "用户名已被注册!";
        if (StringUtil.isNotBlank(name)) {
            user = userService.getCond(new User().setName(name));
        } else if (StringUtil.isNotBlank(email)) {
            user = userService.getCond(new User().setEmail(email));
            msg = "邮箱已被注册";
        } else if (StringUtil.isNotBlank(phone)) {
            user = userService.getCond(new User().setPhone(phone));
            msg = "手机号已被注册";
        }
        if (user == null) {
            return ResponseValidate.ok();
        }
        return ResponseValidate.fail().setMsg(msg);
    }


    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResponseResult register(@RequestBody User user) {
        String pass = StringUtil.md5(user.getPass(), user.getName());
        user.setPass(pass).setCreated(new Date()).setStatus(1).setRoleId(0);
        userService.add(user);
        //添加默认游客角色
        userRoleService.add(new UserRole().setUserId(new BigDecimal(user.getId()).longValue()).setRoleId(Constants.ANONYMOUS_ROLE_ID));
        return ResponseResult.ok();
    }

}

